﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Practices.Unity;
using Baosight.Platform.Core.ServiceModel;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.UI;
using Baosight.Platform.Core;
using Baosight.ZNH.ZMCommon;
using Telerik.Windows.Controls;
using Baosight.ZNH.ZMCP.UI.PopWindows;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Telerik.Windows.Controls.GridView;
using System.Windows.Browser;

namespace Baosight.ZNH.ZMCP.UI
{
    /// <summary>
    /// 月度生产计划
    /// </summary>
    /// Title:ZMCP12
    /// Copyright:Baosight Software LTD.co Copyright (c) 2011
    /// Company:上海宝信软件股份有限公司
    /// Author: 高平
    /// Version: 1.0
    /// History:
    ///       2011-07-11  高平   [创建]
    ///  
    public partial class ZMCP12 : EFViewCmes
    {

        public ZMCP12()
        {
            InitializeComponent();
            base.BeforeAction += OnBeforeAction;
            
        }

        /// <summary>
        /// 新增/修改前设置属性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnBeforeAction(object sender, EventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.EFGridCheckedRows = this.grid.GetCheckedEIRows();
            base.ViewProperty = _view;
        }

        /// <summary>
        /// 点击新增按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnInsertButtonClick(object sender, RoutedEventArgs e)
        {
            TempButton = sender as Button;
            TempButton.IsEnabled = false;
            if (this.grid.EIBlock.Rows.Count > 0)
            {
                base.OpenEFWindowAlert("只能编制一条月度生产计划", true);
                return;
            }

            EIInfo eiInfo = new EIInfo();
            base.OnInsertButtonClickPopup(eiInfo, "月度生产计划-新增", "insert", null, sender, e);
        }

        /// <summary>
        /// 点击修改按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnUpdateButtonClick(object sender, RoutedEventArgs e)
        {
            TempButton = sender as Button;
            TempButton.IsEnabled = false;
            IList<EIRow> _list = this.grid.GetCheckedEIRows() == null ? new List<EIRow>() : this.grid.GetCheckedEIRows();

            EIRow row = new EIRow();
            if (_list.Count > 0)
            {
                row = BaseTools.GetEIRowByOldEIRow(this.EIDataContext.GetBlock("result").GetColumns(), _list[0]);
            }
            if (_list.Count > 0 && !row["fdPlanStatus"].ToString().Equals("草拟"))
            {
                base.OpenEFWindowAlert("只能修改草拟的生产计划", true);
                return;
            }
            EIInfo eiInfo = new EIInfo();
            EIBlock eIBlock = new EIBlock("result");

            eIBlock.SetRow(0, row);
            eiInfo.AddBlock(eIBlock);
            base.OnUpdateButtonClickPopup(eiInfo, "月度生产计划-修改", "update", null, sender, e);
        }


        /// <summary>
        /// 删除按钮的操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnDeleteButtonClick(object sender, RoutedEventArgs e)
        {
            TempButton = sender as Button;
            TempButton.IsEnabled = false;
            if (!ValidateSelectedRow())
            {
                return;
            }

            IList<EIRow> _list = this.grid.GetCheckedEIRows() == null ? new List<EIRow>() : this.grid.GetCheckedEIRows();
            EIRow row = new EIRow();
            row = BaseTools.GetEIRowByOldEIRow(this.EIDataContext.GetBlock("result").GetColumns(), _list[0]);
            if (!row["fdPlanStatus"].ToString().Equals("草拟"))
            {
                base.OpenEFWindowAlert("只能删除草拟的生产计划", true);
                return;
            }
            if (!row["fdPlanSource"].ToString().Equals("0"))
            {
                base.OpenEFWindowAlert("已经有专业计划上报的数据，不能删除", true);
                return;
            }
            base.OnDeleteButtonClick(sender, e);
        }

        /// <summary>
        /// 生效按钮的操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnPublishButtonClick(object sender, RoutedEventArgs e)
        {
            TempButton = sender as Button;
            TempButton.IsEnabled = false;
            if (!ValidateSelectedRow())
            {
                return;
            }

            IList<EIRow> _list = this.grid.GetCheckedEIRows() == null ? new List<EIRow>() : this.grid.GetCheckedEIRows();
            EIRow row = new EIRow();
            row = BaseTools.GetEIRowByOldEIRow(this.EIDataContext.GetBlock("result").GetColumns(), _list[0]);
            if (!row["fdPlanStatus"].ToString().Equals("草拟"))
            {
                base.OpenEFWindowAlert("只有草拟的生产计划才可以生效", true);
                return;
            }
            if ((row["fdPlanMine"] == null || "".Equals(row["fdPlanMine"])) &&
                (row["fdPlanGrub"] == null || "".Equals(row["fdPlanGrub"])) &&
                (row["fdPlanDeploitation"] == null || "".Equals(row["fdPlanDeploitation"])) &&
                (row["fdPlanProjectNum"] == null || "".Equals(row["fdPlanProjectNum"])))
            {
                base.OpenEFWindowAlert("没有明细记录（或者明细中的计划值都为0），不能生效！", true);
                return;
            }

            base.OnModifyButtonClick("publish", "生效", sender, e);
        }

        /// <summary>
        /// 调整
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnAdjustButtonClick(object sender, RoutedEventArgs e)
        {
            TempButton = sender as Button;
            TempButton.IsEnabled = false;
            if (!ValidateSelectedRow())
            {
                return;
            }

            IList<EIRow> _list = this.grid.GetCheckedEIRows() == null ? new List<EIRow>() : this.grid.GetCheckedEIRows();
            EIRow row = new EIRow();
            row = BaseTools.GetEIRowByOldEIRow(this.EIDataContext.GetBlock("result").GetColumns(), _list[0]);
            if (!row["fdPlanStatus"].ToString().Equals("生效"))
            {
                base.OpenEFWindowAlert("只能调整生效的生产计划", true);
                return;
            }

            base.OnModifyButtonClick("adjust", "调整", sender, e);
        }
        


        /// <summary>
        /// 新增或修改之前的数据传输
        /// 构造新增页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        public override void OpenPopup(EIInfo _eIInfo, string _title, string _dialogType, string _args)
        {
            AddProducePlanMonth addProducePlanMonth = new AddProducePlanMonth(_dialogType);//构造一个新的修改页面
            addProducePlanMonth.EIDataContext = new Platform.Core.UI.EIDataContext();
            addProducePlanMonth.EIDataContext.Update(_eIInfo);
            if ("insert".Equals(_dialogType))
            {
                addProducePlanMonth.fdPlanYear.Value = fdPlanYear.Value;
                addProducePlanMonth.fdPlanMonth.Value = fdPlanMonth.Value;
                addProducePlanMonth.fdEditor.Value = this.EIDataContext.GetAttribute("fdEditor");
                addProducePlanMonth.fdEditDate.Value = DateTime.Now.ToString("yyyy-MM-dd");
                addProducePlanMonth.fdMineUnit.Value = "吨";
                addProducePlanMonth.fdGrubUnit.Value = "米";
                addProducePlanMonth.fdDeploitationUnit.Value = "米";
                addProducePlanMonth.fdTitle.Value = fdPlanYear.Value + "年" + fdPlanMonth.Value + "月生产计划";               
            }
            CmesWindows _popup = new CmesWindows();//构造一个弹出页面
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = _title == null ? "" : _title;//设置Title
            _popup.Content = addProducePlanMonth;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(CmesWindow_Closed);
            _popup.ShowDialog();//模态显示弹出窗口
        }

        /// <summary>
        /// 弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmesWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                //刷新Grid区域
                this.grid.Refresh();
            }

            //按钮生效
            base.TempButtonOpen(true);

            //超链接生效
            if (base.TempHyperlink != null)
            {
                base.TempHyperlink.IsEnabled = true;
                base.TempHyperlink = null;
            }
        }

        /// <summary>
        /// 选中主表一条记录，显示该条记录的从表数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridResult_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangeEventArgs e)
        {
            LoadDetailPlan();
        }

        private void LoadDetailPlan()
        {
            if (this.grid.SelectedItem != null)
            {
                var fdProduceplanId = this.grid.SelectedItem.GetType().GetProperty("fdKeyId").GetValue(this.grid.SelectedItem, null);
                var fdPlanStatus = this.grid.SelectedItem.GetType().GetProperty("fdPlanStatus").GetValue(this.grid.SelectedItem, null);
                var fdPlanYear = this.grid.SelectedItem.GetType().GetProperty("fdPlanYear").GetValue(this.grid.SelectedItem, null);
                var fdPlanMonth = this.grid.SelectedItem.GetType().GetProperty("fdPlanMonth").GetValue(this.grid.SelectedItem, null);
                //采煤计划、掘进计划、接替计划、其他计划，其中防突又分为打钻、抽采、管路安装、水利压裂四个分计划
                Dictionary<string, string> args = new Dictionary<string, string>();
                string fdPlanType = "采煤计划";
                string viewName = "ZMCP02";
                if (tabType.SelectedItem == tabItemMine)
                {
                    fdPlanType = "采煤计划";
                    viewName = "ZMCP02";
                }
                else if (tabType.SelectedItem == tabItemGrub)
                {
                    fdPlanType = "掘进计划";
                    viewName = "ZMCP04";
                }
                else if (tabType.SelectedItem == tabItemOther)
                {
                    fdPlanType = "其他计划";
                    viewName = "ZMCP08";
                }
                
                args.Add("fdProduceplanId", fdProduceplanId.ToString());
                args.Add("fdPlanYear", fdPlanYear.ToString());
                args.Add("fdPlanMonth", fdPlanMonth.ToString());
                args.Add("fdPlanStatus", fdPlanStatus.ToString());
                this.container.LoadView<EFCustomViewContainerPanel>(viewName, args);
            }
            else
            {
                this.container.ClearValue(EFCustomViewContainerPanel.ContentProperty);
            }
        }

        /// <summary>
        /// 重新基类的发布数据方法
        /// 刷新树节点
        /// </summary>
        /// <param name="data"></param>
        public override void OnEIDataPublished(EIInfo data)
        {
            if (null != this.grid.SelectedItem)
            {
                //刷新 “计划总量”
                EIInfo eiInfo = new EIInfo();
                eiInfo.Set("service", "ZMCP12");
                eiInfo.Set("method", "query");
                string fdKeyId = this.grid.SelectedItem.GetType().GetProperty("fdKeyId").GetValue(this.grid.SelectedItem, null) as string;
                EIBlock block = eiInfo.AddBlock(EIConstants.QueryStatusBlock);

                EIColumn column = new EIColumn();
                column.Name = "fdKeyId";
                block.AddColumn(column);

                EIRow row = new EIRow();
                row.Add("fdKeyId", fdKeyId);
                block.AddRow(row);

                HttpServiceAgent agent = new HttpServiceAgent();
                agent.CallService(eiInfo, CallServiceCompleted);
            }
        }

        /// <summary>
        /// 访问后台的回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CallServiceCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo == null || e.EIInfo.GetStatus() == -1)
            {
            }
            else
            {
                EIRow row = (this.grid.SelectedItem as UIBaseEntity).GetEIRow();
                row["fdPlanMine"] = e.EIInfo.GetBlock(EIConstants.ResultBlock).Get(0, "fdPlanMine");
                row["fdPlanGrub"] = e.EIInfo.GetBlock(EIConstants.ResultBlock).Get(0, "fdPlanGrub");
                row["fdPlanDeploitation"] = e.EIInfo.GetBlock(EIConstants.ResultBlock).Get(0, "fdPlanDeploitation");
                row["fdPlanProjectNum"] = e.EIInfo.GetBlock(EIConstants.ResultBlock).Get(0, "fdPlanProjectNum");
            }
        }

        /// <summary>
        /// 选择页签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabType_SelectionChanged(object sender, RoutedEventArgs e)
        {
            LoadDetailPlan();
        }

        /// 校验选中的行
        /// </summary>
        private bool ValidateSelectedRow()
        {
            IList<EIRow> _list = this.grid.GetCheckedEIRows() == null ? new List<EIRow>() : this.grid.GetCheckedEIRows();

            if (_list.Count > 1)
            {
                base.OpenEFWindowAlert("只能选择一条生产计划", true);
                return false;
            }

            if (_list.Count == 0)
            {
                base.OpenEFWindowAlert("请先选择一条生产计划", true);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 退回按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnQuitButtonClick(object sender, RoutedEventArgs e)
        {
            TempButton = sender as Button;
            TempButton.IsEnabled = false;

            if (ValidateSelectedRow())
            {
                EIRow row = this.grid.GetCheckedEIRows()[0];
                if (!(row["fdPlanStatus"].ToString().Equals("草拟") && !row["fdPlanSource"].ToString().Equals("3")))
                {
                    base.OpenEFWindowAlert("只有未调整过的草拟计划可以退回！", true);
                    return;
                }
                
                EIInfo eiInfo = new EIInfo();
                eiInfo.Set(EIConstants.ServiceNameKey, "ZMCP12");
                eiInfo.Set(EIConstants.MethodNameKey, "queryPropessionalPlan");
                EIBlock eIBlock = eiInfo.AddBlock("result");
                eIBlock.SetColumns(this.grid.EIBlock.Columns);
                eIBlock.SetRows(this.grid.CheckedEIRows);

                this.Submit(eiInfo, FindPropessionalPlanCompleted);
            }
        }

        /// <summary>
        /// 查询专业计划
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FindPropessionalPlanCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status != -1)
            {
                QuitPlanItam view = new QuitPlanItam();//构造一个新的修改页面
                view.EIDataContext = new Platform.Core.UI.EIDataContext();
                view.EIDataContext.Update(e.EIInfo);

                view.fdKeyId.Value = this.grid.GetCheckedEIRows()[0]["fdKeyId"];

                CmesWindows _popup = new CmesWindows();//构造一个弹出页面
                _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
                _popup.Header = "选择退回的专业计划";//设置Title
                _popup.Content = view;//让新增页面在弹出窗口显示
                _popup.Closed += new EventHandler<WindowClosedEventArgs>(QuitCmesWindow_Closed);
                _popup.ShowDialog();//模态显示弹出窗口
            }
            else
            {
                base.OpenEFWindowAlert(e.EIInfo.GetMsg(), true);
            }
        }

        /// <summary>
        /// 退出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QuitCmesWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                //刷新从表
                if (this.grid.SelectedItem != null)
                {
                    if (this.grid.GetCheckedEIRows()[0]["fdKeyId"].Equals(this.grid.SelectedItem.GetType().GetProperty("fdKeyId").GetValue(this.grid.SelectedItem, null)))
                    {
                        LoadDetailPlan();
                    }
                }

                //刷新 “计划总量”
                EIInfo eiInfo = new EIInfo();
                eiInfo.Set("service", "ZMCP12");
                eiInfo.Set("method", "query");
                EIBlock block = eiInfo.AddBlock(EIConstants.QueryStatusBlock);

                EIColumn column = new EIColumn();
                column.Name = "fdKeyId";
                block.AddColumn(column);

                EIRow row = new EIRow();
                row.Add("fdKeyId", this.grid.GetCheckedEIRows()[0]["fdKeyId"]);
                block.AddRow(row);

                HttpServiceAgent agent = new HttpServiceAgent();
                agent.CallService(eiInfo, CallServiceCompleted);                
            }

            //按钮生效
            base.TempButtonOpen(true);
        }

        /// <summary>
        /// 打印某个月的报表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnPrintButtonClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;

            if (BeforeAction != null)
            {
                BeforeAction.Invoke(null, null);
            }

            int count = this.ViewProperty.EFGridCheckedRows.Count;
            if (count <= 0)
            {
                this.OpenEFWindowAlert("请选择一条记录进行打印！", true);
                return;
            }
            else if (count > 1)
            {
                this.OpenEFWindowAlert("只能选择一条记录进行打印！", true);
                return;
            }
            else
            {
                string fdKeyId = this.grid.GetCheckedEIRows()[0]["fdKeyId"].ToString();
                string fdPlanYear = this.grid.GetCheckedEIRows()[0]["fdPlanYear"].ToString();
                string fdPlanMonth = this.grid.GetCheckedEIRows()[0]["fdPlanMonth"].ToString();
                string planLastMoth = (int.Parse(fdPlanMonth) - 1).ToString();
                string planLastYear = fdPlanYear;
                if (fdPlanMonth.Equals("1"))
                {
                    planLastMoth = "12";
                    planLastYear = (int.Parse(fdPlanYear) - 1).ToString();
                }
                Uri uri = Uploader.ConstructAbsoluteUri("../admin/RunmaxReport.jsp?projectName=ProfessionalPlan&reportName=producePlanReport&keyId=" + fdKeyId + "&year=" + fdPlanYear + "&month=" + fdPlanMonth + "&lastMonth=" + planLastMoth + "&lastYear=" + planLastYear);
                HtmlPage.Window.Navigate(uri, "_blank");
                base.TempButtonOpen(true);//按钮生效
            }

        }
    }
}
